//xhr 短连接请求
//TODO:timeout设置可能存在问题待测试。
WUJIANGHAI.xhr = function(options){
	var xhr = cc.loader.getXMLHttpRequest();
	//初始化options
	var serverDataType = options.hasOwnProperty("serverDataType")?options.serverDataType:"robj";
	var anyc = options.hasOwnProperty("anyc")?options.anyc:true;
	var method = options.hasOwnProperty("method")?options.method.toUperCase():"POST";
	var returnType = options.hasOwnProperty("returnType")?options.returnType.toLowerCase():"json";
	var url = options.hasOwnProperty("url")?options.url:(WUJIANGHAI.localurl+WUJIANGHAI.action_test);
	var params = options.hasOwnProperty("params")?options.params:"";
	var timeout = options.hasOwnProperty("timeout")?options.timeout:5000;//timeout时间默认五秒
	var success = options.hasOwnProperty("success")?options.success:null;
	var failure = options.hasOwnProperty("failure")?options.failure:null;
	var timeoutCallback = options.hasOwnProperty("timeoutCallback")?options.timeoutCallback:null
			
	var timeoutFun = null;
	if(anyc){
		timeoutFun =  setTimeout(function(){
			if(xhr.readyState != 4) {
				xhr.abort();
				clearTimeout(timeoutFun);
				if(timeoutCallback)
					timeoutCallback(xhr);
			}    
		}, timeout);
	}
	 
	xhr.open(method, url,anyc);
	xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
	//xhr.setRequestHeader("Content-Type","text/plain;charset=UTF-8");
	xhr.onreadystatechange = function () {
		var httpStatus = xhr.statusText;
		if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status <= 207)) {
			if(anyc){
				if(timeoutFun){
					clearTimeout(timeoutFun);
				}
			}
			var response = xhr.responseText;
			var ret = response;
			if(returnType=="json"){
				try{
					ret  = JSON.parse(response);
				} catch(e){
					cc.log("json数据格式有问题！");
				}
			}
			if(success)
				success(ret,xhr);
		}	else {
			if(failure)
				failure(xhr);
		}
	};
	var sendstr= "";
	if(params!=null&&params!=""){
		if(WUJIANGHAI.getTypeof(params)!="string"){
			params = WUJIANGHAI.jsonToString(params);
		}
		sendstr=serverDataType+"="+params;
	}
	xhr.send(sendstr);
}
WUJIANGHAI.getTypeof = function(obj){
	return typeof obj;
} 
//方法执行时间统计 ms
WUJIANGHAI.executionTime = function(excutfun){
	var start = new Date().getTime();//起始时间
	excutfun();
	var end = new Date().getTime();//接受时间
	cc.log((end - start)+"ms");
	return (end - start);
}
WUJIANGHAI.jsonToString = function(json){
	return JSON.stringify(json); 
}
//正则判断账号：数字字母下划线长度在3-20之间。
WUJIANGHAI.testUsername = function(str){
	var reg = new RegExp("^[a-zA-Z0-9_@\.]{4,30}$");
	return reg.test(str);
}

//正则判断密码格式：长度。
WUJIANGHAI.testPassword= function(str){
	if(str.length>=6&&str.length<=15){
		return true;
	} else {
		return false;
	}
}
WUJIANGHAI.sizeof = function(str){
	var byteLen=0,len=str.length;
	if(str){
		for(var i=0; i<len; i++){
			if(str.charCodeAt(i)>255){
				byteLen += 2;
			}
			else{
				byteLen++;
			}
		}
		return byteLen;
	}
	else{
		return 0;
	}
}
//hero test
WUJIANGHAI.CCAM_Animation = cc.Node.extend({
	m_pAnimRoot:null,
	m_szName:null,
	m_pCurAnimSet:null,
	m_fTimePefFrame:0.05,
	m_pAnimData:null,
	_pFileName:"",
	m_nLoop:0,
	m_nCurFrame:0,
	m_fCurTime:0.0,
	ctor:function(pFileName){
		this._super();
		if(!pFileName){
			pFileName = "res/spine/NA"
		}
		this.m_pAnimRoot = null;
		this.m_szName = null;
		this.m_pCurAnimSet = null;
		this.m_fTimePefFrame = 0.05;
		this.m_fCurTime = 0.0;
		this._pFileName = pFileName;
		try{
			this.initWithFile(pFileName);
		}catch(e){
			cc.log(e.message)
		}
		this.scheduleUpdate();
	},
	initWithFile:function(pFileName)
	{
		return this.LoadFromFile(pFileName);
	},
	LoadFromFile:function(pFileName){
		var cache = new WUJIANGHAI.CCAM_AnimationCache();
		cache.addAnimationDataWithFile(pFileName);
		var pAnimData = cache.getAnimationData(pFileName);
		//var pAnimData = this.getAnimationData(pFileName);
		if (!pAnimData)
		{
			if (!this.LoadFromFile(pFileName))
			{
				return false;
			}
		}
		this.initWithData(pAnimData);
		return true;
	},
	
	initWithData:function(pAnimData){
		//m_pAnimRoot = new cc.Node();
		//this.m_pAnimRoot = new cc.SpriteBatchNode(pAnimData.m_pTexture);
		this.m_pAnimRoot = new cc.SpriteBatchNode(this._pFileName+"/"+"sheet.pvr");
		// 解析使用的紋理
		try{
			for (var i = 0; i < pAnimData.m_vecBone.length; i++)
			{
				var pSpriteFrame = pAnimData.m_vecBone[i];
				
				var nIndex = pAnimData.m_vecBoneIndex[i];
				//var pSprite = cc.Sprite.createWithSpriteFrameName(pSpriteFrame);
				var pSprite = new cc.Sprite();
					pSprite.initWithSpriteFrame(pSpriteFrame.getSpriteFrame());
				//pSprite.setSpriteFrame(pSpriteFrame.getSpriteFrame())
				pSprite.setVisible(false);
				pSprite.setTag(nIndex*1);
				pSprite.setAnchorPoint(0.5, 0.4);
				this.m_pAnimRoot.addChild(pSprite);
				this.m_pAnimRoot.reorderChild(pSprite, nIndex*1);
				cc.log("cc"+this.m_pAnimRoot.getChildByTag(2)+"=="+i)
			}
		}catch (e) {
			cc.log(e.message)
		}
		this.addChild(this.m_pAnimRoot);
		this.m_pAnimData = pAnimData;
		//m_pAnimData.retain();
		//this.setOpacity(50);
		this.setCascadeOpacityEnabled(true);
		this.m_pAnimRoot.setCascadeOpacityEnabled(true);
		this.PlayByIndex(1);
		//this.Play("Idle");
		return true;
	},
	PlayByIndex:function(nIndex){
		var pName = this.m_pAnimData.m_vecAnimationSetsName[nIndex];
		//cc.log(pName)
		this.Play(pName);
	},
	Play:function(pAnim){
		for (var i = 0; i < this.m_pAnimData.m_vecAnimationSetsName.length; i++)
		{
			if (this.m_pAnimData.m_vecAnimationSetsName[i] == pAnim)
			{
				this.m_nAnimIndex = i;
				break;
			}
		}
		this.m_pCurAnimSet = this.m_pAnimData.m_mapAnimationSets[pAnim];
		
		//TODO: getframeCount()
		this.m_nFrameCount = this.m_pCurAnimSet.GetFrameCount();
		//Clear();
		this.m_fCurTime = 0.0;
	},
	SetTimeOneFrame:function(fTime){
		this.m_fTimePefFrame = fTime;
	},
	SetAnimationRate:function(nRate){
		this.SetTimeOneFrame(1.0 / nRate);
	},
	GetAnimationRate:function(){
		return 1 / this.m_fTimePefFrame;
	},
	GetName:function(){
		return this.m_pAnimData.m_szName; 
	},
	AnimationCount:function(){
		return this.m_pAnimData.m_vecAnimationSetsName.length;
	},
	GetAnimNameByIndex:function(){
		if (nIndex >= this.m_pAnimData.m_vecAnimationSetsName.length)
		{
			nIndex = 0;
		}
		return this.m_pAnimData.m_vecAnimationSetsName[nIndex];
	},
	update:function (deltaTime) 
	{
			
		if(!this.m_pCurAnimSet || !this.isVisible())
			return ;

		this.m_fCurTime += deltaTime;
		var nCurFrame = Math.round(this.m_fCurTime /  this.m_fTimePefFrame); 
		//if (true)
		if (nCurFrame >  this.m_nCurFrame)
		{
			this.m_nCurFrame = nCurFrame;
			var nFrame =  Math.round(this.m_nCurFrame %  this.m_nFrameCount);
			var nLoop = Math.round(this.m_nCurFrame /  this.m_nFrameCount);
			
			if (nLoop >  this.m_nLoop)
			{
				this.m_nLoop = nLoop;
				this.m_nCurFrame--;
				return;
			}
			this.m_pCurAnimSet.Update(nFrame,this.m_pAnimRoot) ;
		
		}
	},
	setDebugDraw:function( bDebugDraw)
	{
		for (var i in this.m_pAnimRoot.getChildren())
		{
			var pSprite = this.m_pAnimRoot.getChildren()[i];
			pSprite.debugDraw(bDebugDraw);
	    }
	}
})

WUJIANGHAI.CCAM_AnimationCache = function(){
	this.m_mapAnimData={};
	this.getAnimationData=function(fca){
		for(var i in this.m_mapAnimData){
			return this.m_mapAnimData[i];
		}
		return null;
	}
	this.addAnimationDataWithFile=function(fca){
//		for(var i in this.m_mapAnimData){
//			return;
//		}
		///TODO:
		try{
			var pAnimData = new WUJIANGHAI.CCAM_AnimationData();
			pAnimData.LoadFromFile(fca);
			this.m_mapAnimData[fca]=  pAnimData;
		}catch(e){
			cc.log(e.message)
		}
		
	}
}

WUJIANGHAI.CCAM_AnimationSet = function(){
	this.m_vecFrame = [];
	this.AddFrame = function(pFrame){
		this.m_vecFrame.push(pFrame);
	}
	this.GetFrameCount = function(){
		return this.m_vecFrame.length;
	}
	this.Update = function(nCurFrame,pAnimNode){
		this.m_vecFrame[nCurFrame].Update(pAnimNode);
	}
}

WUJIANGHAI.CCAM_AnimationData = function(){
	this.m_vecAnimationSetsName=[];
	this.m_pTexture=null;
	this.m_vecBone=[];
	this.m_vecBoneIndex=[];
	this._spriteFrames=[];
	this.m_mapAnimationSets={};
	this.m_szName=null;
	this.m_fPosScale=null;
	
	this.GetName = function(){
		
	}
	this.ReadValue = function(obj){
		obj.nLength = obj.pData[obj.pPos];
		obj.pPos += obj.flag;
	}
	this.ReadIntValue = function(obj){
		var buffer = new ArrayBuffer(100);
		var dv = new DataView(buffer);
		var a = new Uint8Array(buffer);
		a[0] = obj.pData[obj.pPos];
		a[1] = obj.pData[obj.pPos+1];
		a[2] = obj.pData[obj.pPos+2];
		a[3] = obj.pData[obj.pPos+3];

		//cc.log(dv.getFloat32(0));
		//cc.log(obj.pData[obj.pPos]+"-"+obj.pData[obj.pPos+1]+"-"+obj.pData[obj.pPos+2]+"-"+obj.pData[obj.pPos+3]+"="+dv.getFloat32(0,true).toFixed(4));
		obj.nLength = dv.getInt32(0,true);//.toFixed(4);
		obj.pPos += 4;
	}
	this.ReadFloatValue = function(obj){
		var buffer = new ArrayBuffer(100);
		var dv = new DataView(buffer);
		var a = new Uint8Array(buffer);
		a[0] = obj.pData[obj.pPos];
		a[1] = obj.pData[obj.pPos+1];
		a[2] = obj.pData[obj.pPos+2];
		a[3] = obj.pData[obj.pPos+3];

		//cc.log(dv.getFloat32(0));
		//cc.log(obj.pData[obj.pPos]+"-"+obj.pData[obj.pPos+1]+"-"+obj.pData[obj.pPos+2]+"-"+obj.pData[obj.pPos+3]+"="+dv.getFloat32(0,true).toFixed(4));
		obj.nLength = dv.getFloat32(0,true);//.toFixed(4);
		obj.pPos += 4;
	}
	this.ReadName = function(obj){
		var nPos = obj.pPos;
		var pName = obj.pName;
		var pData = obj.pData; 
		var pPos = obj.pPos;
		var flag = obj.flag;

		var nLength = 0;
		obj.nLength = 0;
		this.ReadValue(obj); 
		nLength = obj.nLength;
		var nPos = obj.pPos;

		//obj.pPos = nPos + obj.nLength;  
		var cd = nLength;//obj.pPos+1;// 每个字符占用2个字节
		//var cd = 8;// 每个字符占用2个字节 
		var start = nPos;
		//	cc.log("kuan:"+cd+"kaishi:"+start)

		var buf = new ArrayBuffer(cd); 
		var bufView = new Uint8Array(buf);
		var flag = 0;
		for (var i=start; i<start+cd; i++) {
			bufView[flag] = pData[i];
			flag++;
		}    
		var orgStr = String.fromCharCode.apply(null, new Uint8Array(buf));
		//cc.log(orgStr.substring(0,orgStr.length-1))
		//cc.log(orgStr.substring(0,orgStr.length-1))
		obj.pName = orgStr;
     	obj.pPos += cd; 
	}
	this.AnimationCount = function(){
		return this.m_vecAnimationSetsName.length;
	}
	this.GetAnimNameByIndex = function(nIndex){
		if(nIndex >= this.m_vecAnimationSetsName.length)
		{
			nIndex = 0;
		}
		return this.m_vecAnimationSetsName[nIndex]; 
	}
	this.GetFrames= function(){
		return this._spriteFrames;
	}
	this.getFileDataFromZip = function(zipFile,fileName,size){
		if (null == zipFile || null == fileName || null == size)
			return null;

		var zipData = jsb.fileUtils.getDataFromFile(zipFile);
		if (zipData==null)
			return null;
		var zip =null;
		//var zip = ZipFile.createWithBuffer(zipData.getBytes(), zipData.getSize());
		if (null == zip)
			return null;

		size = 0;
		var data = zip.getFileData(fileName, size);
		zip = null;
		if (null == data || size <= 0)
		{
			size = 0;
			///free(data);
			return null;
		}

		return data;
	}
	this.getFileDataFromZipPvr = function(zipFile,fileName,size){
		if (null == zipFile || null == fileName || null == size)
			return null;

	
		var data = jsb.fileUtils.getStringFromFile(fileName);
	

		return data;
	}
	this.fomatSize = function(str){
		var tem = str.replace(/{/g,"").replace(/}/g,"") 
		var num = tem.split(',');
		return cc.size(num[0],num[1]);
	}
	this.fomatRect = function(str){
		var tem = str.replace(/{/g,"").replace(/}/g,"") 
		var num = tem.split(',');
		return cc.rect(num[0],num[1],num[2],num[3]);
	}
	this.fomatPoint = function(str){
		var tem = str.replace(/{/g,"").replace(/}/g,"") 
		var num = tem.split(',');
		return cc.p(num[0],num[1]);
	}
	this.LoadFromFile = function(pFileName){
		if (this.m_szName)
		{
			this._spriteFrames=[];
			//CC_SAFE_RELEASE(this.m_pTexture);
			this.m_szName = null;
			this.m_vecAnimationSetsName = null;
			this.m_mapAnimationSets = {};
			this.m_vecBone = [];
			this.m_vecBoneIndex = [];
		}

		var strPreFix = pFileName;
		strPreFix += "/";

		// 创建纹理
		//var pData = this.getFileDataFromZipPvr(pFileName, "res/spine/AA/sheet.pvr", nSize);
		
		var image = new cc.Sprite(strPreFix+'sheet.pvr');
			//image.loadTexture(pData)
//		var image = new Image();
//		if (!image.initWithImageData(pData, nSize))
//		{
//			//free(pData);
//			return false;
//		}
		//this.m_pTexture = image;//new cc.Texture2D();
		this.m_pTexture = strPreFix+'sheet.pvr';
		//this.m_pTexture.initWithImage(image);
		//CC_SAFE_RELEASE(image);
		//free(pData);

		// 创建SpriteFrame
		var texture = this.m_pTexture;
		var dictionary = jsb.fileUtils.getValueMapFromFile(jsb.fileUtils.getWritablePath()+strPreFix+"plist");
		//allen TODO:
		var framesDict = dictionary["frames"];//json
		var format = 0;

		// get the format
		if(dictionary.hasOwnProperty("metadata")){
			var metadataDict = dictionary["metadata"];//.asValueMap();
			format = Math.round(metadataDict["format"]*1);
		}
		

		// check the format
		//CCASSERT(format >= 0 && format <= 3, "format is not supported for SpriteFrameCache addSpriteFramesWithDictionary:textureFilename:");
		
		for(var i in framesDict){
			var frameDict = framesDict[i];//.asValueMap();
			
			
			var spriteFrameName = i;
			var spriteFrame = null;
			if (format == 0)
			{
				var x = frameDict["x"]*1;
				var y = frameDict["y"]*1;
				var w = frameDict["width"]*1;
				var h = frameDict["height"]*1;
				var ox = frameDict["offsetX"]*1;
				var oy = frameDict["offsetY"]*1;
				var ow = frameDict["originalWidth"]*1;
				var oh = frameDict["originalHeight"]*1;
				// check ow/oh
				if (!ow || !oh)
				{
					cc.log("cocos2d: WARNING: originalWidth/Height not found on the SpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist");
				}
				// abs ow/oh
				ow = Math.abs(ow);
				oh = Math.abs(oh);
				// create frame
				spriteFrame = new cc.Sprite(texture,
						cc.rect(x, y, w, h),
						false,
						cc.math.Vec2(ox, oy),
						cc.size(ow, oh)
				);
			}
			else if (format == 1 || format == 2)
			{
				var frame = frameDict["frame"];
				//cc.log(frame)
				var rotated = false;

				// rotation
				if (format == 2)
				{
					rotated = frameDict["rotated"];
				}

				var offset = frameDict["offset"];
				var sourceSize = frameDict["sourceSize"];
				// create frame
				spriteFrame = new cc.Sprite(texture,
						this.fomatRect(frame),
						rotated,
						this.fomatPoint(offset)
						//,this.fomatSize(sourceSize)
				);
			}
			else if (format == 3)
			{
				// get values
				var spriteSize = frameDict["spriteSize"];
				var spriteOffset = frameDict["spriteOffset"];
				var spriteSourceSize =frameDict["spriteSourceSize"];
				var textureRect = frameDict["textureRect"];
				var textureRotated = frameDict["textureRotated"];

				// create frame
				spriteFrame = new cc.Sprite(texture,
						cc.rect(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height),
						textureRotated,
						spriteOffset,
						spriteSourceSize);
			}

			// add sprite frame
			
			this._spriteFrames[spriteFrameName]=spriteFrame;
		}


		// 创建动画数据
		pData = jsb.fileUtils.getDataFromFile(jsb.fileUtils.getWritablePath()+strPreFix+"cha");
		var nPos = 0;
		//this.m_szName = new char[100];
		this.m_szName = "";
		var pPos = 0; 
		var pName = "";
		var flag = 4;
		var snode = {flag:flag,pName:pName,pData:pData,pPos:pPos,nLength:0};
		this.ReadName(snode);
		//cc.log(snode.pName)

		var strName =  this.m_szName;

		this.m_fPosScale = 0.1;
		var nIndex2 = strName.indexOf("/");
		if(nIndex2 != -1)
		{
			strName = strName.substr(nIndex2+1);

			nIndex2 = strName.indexOf("_");
			var nIndex3 = strName.indexOf("_", nIndex2+1);
			var strTag = strName.substr(nIndex2+1, nIndex3-nIndex2-1);
			if(strTag == "UI")
			{
				this.m_fPosScale = 0.5;
			}
		}


		snode.flag = 4;
		this.ReadIntValue(snode);
		
		//this.m_vecBone.reserve(nTextureNum);指定容易存储个数
		//this.m_vecBone = [];
		var nTextureNum=snode.nLength;
		var pName = "";

		//cc.log("LoadTexture");
		// 解析使用的紋理
		for(var i =0; i < nTextureNum; i++)
		{
			this.ReadName(snode);
			this.ReadName(snode);
			//cc.log(snode.pName)
			var strFrameName = snode.pName + ".png";
			snode.flag = 4;
			this.ReadIntValue(snode);
			
			this.m_vecBone.push(this._spriteFrames[strFrameName]);
			this.m_vecBoneIndex.push(snode.nLength);
		}

		//cc.log("LoadAnimation");
		// 解析動畫	
		snode.flag = 4;
		this.ReadIntValue(snode);
		var nAnimNum=snode.nLength;
		for(var a = 0; a < nAnimNum; a++)
		{
			this.ReadName(snode);
			//cc.log(snode.pName)
			var strAnimName = snode.pName;
			snode.pPos += 4;

			pAnimSet = new WUJIANGHAI.CCAM_AnimationSet();
			snode.flag = 4;
			this.ReadIntValue(snode);
			var nFrameNum = snode.nLength;
			for(var i = 0; i < nFrameNum; i++)
			{
				var pFrame = new WUJIANGHAI.CCAM_Frame();//TODO
				//pFrame.retain();

				//var nLoop;
				snode.flag = 4;
				this.ReadIntValue(snode);
				var nSoundNum = snode.nLength;
				for (var nIndex = 0; nIndex < nSoundNum; nIndex++)
				{	
					snode.flag = 4;
					this.ReadValue(snode);

					this.ReadName(snode);
					pFrame.AddSound(snode.pName);
					//cc.log(snode.pName)

					snode.pPos += 32;
					snode.flag = 4;
					this.ReadValue(snode);
				}
				snode.flag = 4;
				this.ReadIntValue(snode);
				var nSpriteCount = snode.nLength;
				
				if(nSpriteCount==null) continue;
				//cc.log(nSpriteCount)
				for(var j = 0; j < nSpriteCount; j++)
				{
					snode.flag = 2;
					this.ReadValue(snode);
					var nTextureID = snode.nLength;
					//cc.log("骨骼ID"+nTextureID);
					//unsigned char Opactiy;
					snode.flag = 1;
					this.ReadValue(snode);
					var Opactiy = snode.nLength;
					//cc.log("透明度："+Opactiy);
//					for(var iii=0;iii<80;iii++){
//						cc.log("op:"+pData[snode.pPos+iii])
//					}
//					cc.log("end");
//					return;
					var trans = {};
					//TODO;
					snode.flag = 4;
					this.ReadFloatValue(snode);
					trans.a = snode.nLength;
					this.ReadFloatValue(snode);
					trans.b = snode.nLength;
					this.ReadFloatValue(snode);
					trans.c = snode.nLength;
					this.ReadFloatValue(snode);
					trans.d = snode.nLength;
					this.ReadFloatValue(snode);
					trans.tx = snode.nLength;
					this.ReadFloatValue(snode);
					trans.ty = snode.nLength;
					trans.c *= -1.0;
					trans.b *= -1.0;

					trans.tx *= this.m_fPosScale;
					trans.ty *= -this.m_fPosScale;
					
					//cc.log(strAnimName+"原始："+nTextureID);
					//cc.log('a：'+trans.a+"b:"+trans.b+"c:"+trans.c+"d:"+trans.d+"x:"+trans.tx+" y:"+trans.ty);
					
					pFrame.AddElement(nTextureID, Opactiy, trans);
				}
				pAnimSet.AddFrame(pFrame);
			}
			cc.log(strAnimName)
			this.m_mapAnimationSets[strAnimName]= pAnimSet;
			//cc.log("strAnimName:"+strAnimName);
			this.m_vecAnimationSetsName.push(strAnimName);
		}
		pName = "";	
		return true;
	}
}

WUJIANGHAI.CCAM_Frame = function(){
	this.m_vecFrameElement= [];
	this.m_strSoundName = "";
	this.AddSound = function(strSoundName){
		this.m_strSoundName = strSoundName;
//		#if CC_TARGET_PLATFORM == CC_PLATFORM_WP8
//		if(m_strSoundName.size() > 0)
//		{
//			m_strSoundName.replace(m_strSoundName.size()-3, 3, "wav");
//		}
//		#endif
	}
	this.AddElement=function(TextureID,Opacity,trans){
		var pElement = {
			TextureID:"",
			Opacity:0,
			trans:null
		};

		pElement.TextureID = TextureID;
		pElement.Opacity = Opacity;
		pElement.trans = trans;
		this.m_vecFrameElement.push(pElement);
		return pElement;
	}
	this.Update=function(pAnimNode){
//		if(this.m_strSoundName.length> 0)
//		{
//			//SimpleAudioEngine::getInstance()->playEffect((std::string("sound/")+m_strSoundName).c_str(), false);
//			//CCLOG(m_strSoundName.c_str());
//		}
 
		for (var i in pAnimNode.getChildren())
		{
			pAnimNode.getChildren()[i].setVisible(false);
		}

		var pos;
		var scale;
		var skew;
		for(var i = 0; i < this.m_vecFrameElement.length; i++)
		{
			//cc.log("textureID:"+this.m_vecFrameElement[i].TextureID)
			var pSprite = pAnimNode.getChildByTag(this.m_vecFrameElement[i].TextureID*1);
			if(pSprite==null) {
				cc.log("sprite null:"+this.m_vecFrameElement[i].TextureID)
				continue;
			}
			var abcde = {
				trans:this.m_vecFrameElement[i].trans,  
				pos:{}, scale:{},  skew:{}	
			}
			try{
				WUJIANGHAI.MatrixTransformer.getGetTSKOBJ(abcde);
				//pSprite.x = abcde.pos.x;
				//pSprite.y = abcde.pos.y;
				//cc.log(abcde.pos.x+"---"+abcde.pos.y)
				//cc.log(abcde.pos.x+"---"+abcde.pos.y)
				pSprite.setPosition(cc.p(abcde.pos.x,abcde.pos.y));
				pSprite.setScale(abcde.scale.x, abcde.scale.y);
				pSprite.setRotationSkewX(abcde.skew.x);
				pSprite.setRotationSkewY(-abcde.skew.y);
				pSprite.setOpacity(this.m_vecFrameElement[i].Opacity);

				pSprite.setVisible(true);
				pAnimNode.reorderChild(pSprite, i);
			}catch(e){
				cc.log(e.message)
			}
			
		}
	}
	this.SetPosScale= function(fScale){
		for(var i = 0; i < this.m_vecFrameElement.length; i++)
		{
			var addTrans = this.m_vecFrameElement[i].trans;
			addTrans.tx *= fScale;
			addTrans.ty *= fScale;
		}
	}
}
WUJIANGHAI.MatrixTransformer = {
	getScaleX:function(m){
		return Math.sqrt(m.a*m.a + m.b*m.b);
	},
	setScaleX:function(m,scaleX){
		var oldValue = this.getScaleX(m);
		// avoid division by zero 
		if (oldValue)
		{
			var ratio = scaleX / oldValue;
			m.a *= ratio;
			m.b *= ratio;
		}
		else
		{
			var skewYRad = this.getSkewYRadians(m);
			m.a = cos(skewYRad) * scaleX;
			m.b = sin(skewYRad) * scaleX;
		}
	},
	getScaleY:function(m){
		return Math.sqrt(m.c*m.c + m.d*m.d);
	},
	setScaleY:function(m,scaleY){
		var oldValue = this.getScaleY(m);
		// avoid division by zero 
		if (oldValue)
		{
			var ratio = scaleY / oldValue;
			m.c *= ratio;
			m.d *= ratio;
		}
		else
		{
			var skewXRad = getSkewXRadians(m);
			m.c = -Math.sin(skewXRad) * scaleY;
			m.d =  Math.cos(skewXRad) * scaleY;
		}
	},
	getSkewXRadians:function(m)
	{
		return Math.atan2(-m.c, m.d);
	},
	setSkewXRadians:function(m,  skewX)
	{
		var scaleY = this.getScaleY(m);
		m.c = -scaleY * Math.sin(skewX);
		m.d =  scaleY * Math.cos(skewX);
	},
	getSkewYRadians:function(m)
	{
		return Math.atan2(m.b, m.a);
	} ,
	setSkewYRadians:function(m,  skewY)
	{
		var scaleX = this.getScaleX(m);
		m.a = scaleX * Math.cos(skewY);
		m.b = scaleX * Math.sin(skewY);
	},

	getSkewX:function(m)
	{
		return Math.atan2(-m.c, m.d) * (180/Math.PI);
	},
	setSkewX:function(m,  skewX)
	{
		this.setSkewXRadians(m, skewX*(Math.PI/180));
	},
	getSkewY:function(m)
	{
		return Math.atan2(m.b, m.a) * (180/Math.PI);
	},

	setSkewY:function(m, skewY)
	{
		setSkewYRadians(m, skewY*(Math.PI/180));
	},
	getRotationRadians:function(m)
	{
		return this.getSkewYRadians(m);
	},
	setRotationRadians:function(m,  rotation)
	{
		var oldRotation = this.getRotationRadians(m);
		var oldSkewX = this.getSkewXRadians(m);
		this.setSkewXRadians(m, oldSkewX + rotation-oldRotation);
		this.setSkewYRadians(m, rotation);		
	},
	getRotation:function(m)
	{
		return this.getRotationRadians(m)*(180/Math.PI);
	},
	setRotation:function(m,  rotation)
	{
		this.setRotationRadians(m, rotation*(Math.PI/180));
	},

	rotateAroundInternalPoint:function(m,  x,  y,  angleDegrees)
	{
		var point = cc.math.Vec2(x, y);
		point = this.PointApplyAffineTransform(point, m);
		m.tx -= point.x;
		m.ty -= point.y;
		m= this.AffineTransformRotate(m,angleDegrees*(Math.PI/180));
		m.tx += point.x;
		m.ty += point.y;
	},
	rotateAroundExternalPoint:function(m,  x,  y,  angleDegrees)
	{
		m.tx -= x;
		m.ty -= y;
		m=this.AffineTransformRotate(m,angleDegrees*(Math.PI/180));
		m.tx += x;
		m.ty += y;
	},
	matchInternalPointWithExternal:function(m, internalPoint, externalPoint)
	{
		var internalPointTransformed = this.PointApplyAffineTransform(internalPoint, m);
		var dx = externalPoint.x - internalPointTransformed.x;
		var dy = externalPoint.y - internalPointTransformed.y;	
		m.tx += dx;
		m.ty += dy;
	},
	getGetTSK:function( trans,  pos, scale,  skew)
	{
		pos.x = trans.tx;
		pos.y = trans.ty;
		scale.x = this.getScaleX(trans);
		scale.y = this.getScaleY(trans);
		skew.x = -this.getSkewX(trans);
		skew.y = this.getSkewY(trans);
	},
	getGetTSKOBJ:function(obj)
	{
		obj.pos.x = obj.trans.tx;
		obj.pos.y = obj.trans.ty;
		obj.scale.x = this.getScaleX(obj.trans);
		obj.scale.y =  this.getScaleY(obj.trans);
		obj.skew.x = - this.getSkewX(obj.trans);
		obj.skew.y =  this.getSkewY(obj.trans);
	},
	getGetTSKRadians:function(trans, pos, scale, skew)
	{
		pos.x = trans.tx;
		pos.y = trans.ty;
		scale.x = this.getScaleX(trans);
		scale.y = this.getScaleY(trans);
		skew.x = -this.getSkewXRadians(trans);
		skew.y = this.getSkewYRadians(trans);
	},

	getGetMatrix:function( trans, matrix)
	{
		//matrix = Mat4::IDENTITY;

		var pos; var scale; var skew;
		this.getGetTSK(trans, pos, scale, skew);


		if (skew.x == -skew.y)
		{
			var sine = Math.sin(skew.x);
			var cosine = Math.cos(skew.x);

			matrix.m[0] = scale.x * cosine;
			matrix.m[1] = scale.x * -sine;
			matrix.m[4] = scale.y * sine;
			matrix.m[5] = scale.y * cosine;
		}
		else
		{
			matrix.m[0] = scale.x * cos(skew.y);
			matrix.m[1] = scale.x * sin(skew.y);
			matrix.m[4] = scale.y * sin(skew.x);
			matrix.m[5] = scale.y * cos(skew.x);
		}

		matrix.m[12] = pos.x;
		matrix.m[13] = pos.y;
	}
}